﻿#include "formrequester.h"
#include "ui_formrequester.h"
#include "widgetutils.h"
#include "commconfig.h"
#include "qstringutils.h"

FormRequester::FormRequester(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormRequester)
{
    ui->setupUi(this);
}

FormRequester::~FormRequester()
{
    saveUiCfg();
    delete ui;
}

void FormRequester::setComm(BaseRequester *req)
{
    _req=req;
    QWidget *w=req->getConfigWidget();
    setCfgWidget(w);
    loadUiCfg();
}

void FormRequester::setCfgWidget(QWidget *w)
{
    QVBoxLayout *vbox = new QVBoxLayout();
    vbox->addWidget(w);
    ui->groupBox->setLayout(vbox);
}

void FormRequester::loadUiCfg()
{
    QString gn=QString("%1_ui").arg(_req->name());
    RequestCfg cfg=CommConfig::instance().getReqCfg(gn);
    ui->chbRecord->setChecked(cfg.isSave);
    ui->chbHex->setChecked(cfg.isHex);
    ui->txtSend->setText(cfg.curCmd);
}

void FormRequester::saveUiCfg()
{
    QString gn=QString("%1_ui").arg(_req->name());
    RequestCfg cfg;
    cfg.isSave=ui->chbRecord->isChecked();
    cfg.isHex=ui->chbHex->isChecked();
    cfg.curCmd=ui->txtSend->text();
    CommConfig::instance().setReqCfg(gn,cfg);
}

void FormRequester::on_btnSend_clicked()
{
    saveUiCfg();
    sendMsg();
}

void FormRequester::sendMsg()
{
    QByteArray arr=ui->chbHex->isChecked()?QByteArray::fromHex(ui->txtSend->text().toUtf8())
                                         :ui->txtSend->text().toUtf8();
    _req->requestNoReply(arr);
    if(ui->chbRecord->isChecked())
    {
        qDebug()<<"发送:"<<ui->txtSend->text();
    }

    QString formattedData = QStringUtils::getFormatString(arr,ui->chbHex->isChecked());
    // 使用HTML格式设置颜色
    QString html = QString("<span style='color:red;'>发送: </span><span>%1</span>").arg(formattedData);
    ui->reciveData->append(html);  // 使用 append 追加内容
}

QString FormRequester::getFormatString(QByteArray arr,bool isHex)
{
    QString formatted = "";
    if(isHex)
    {
        for (int i = 0; i < arr.size(); ++i) {
          formatted += QString(" %1").arg(static_cast<unsigned char>(arr[i]), 2, 16, QLatin1Char('0')).toUpper();
        }
    }
    else
    {
        formatted=QString::fromUtf8(arr);
    }
    return formatted;
}

void FormRequester::on_btnRquest_clicked()
{
    WidgetUtils::Execute(ui->btnRquest,[this]
    {
        QByteArray arr=QByteArray::fromHex(ui->txtSend->text().toUtf8());
        QByteArray rec=_req->request(arr);

        QString formattedData = getFormatString(arr,ui->chbHex->isChecked());
        // 使用HTML格式设置颜色
        QString html = QString("<span style='color:red;'>发送: </span><span>%1</span>"
                               "<span style='color:green;'>  接收: </span><span>%2</span>").arg(formattedData).arg(getFormatString(rec,ui->chbHex->isChecked()));
        ui->reciveData->append(html);  // 使用 append 追加内容
    });
}

void FormRequester::on_btnClear_clicked()
{
    ui->reciveData->clear();
}
